<template>
	<view class="login-container">
		<view class="login-header">
			<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
			<text class="title">日程任务管理系统</text>
		</view>
		
		<!-- 错误信息显示 -->
		<view v-if="errorMsg" class="error-message">
			<text>{{ errorMsg }}</text>
		</view>
		
		<view class="login-form">
			<view class="form-item">
				<text class="label">用户名</text>
				<input v-model="username" placeholder="请输入用户名" />
			</view>
			<view class="form-item">
				<text class="label">密码</text>
				<input v-model="password" type="password" placeholder="请输入密码" />
			</view>
			<view class="form-actions">
				<button class="login-btn" @tap="login" :disabled="isLoading" type="primary">
					{{ isLoading ? '登录中...' : '登录' }}
				</button>
				<button class="register-btn" @tap="showRegister" :disabled="isLoading">注册新账号</button>
			</view>
			
			<!-- 调试信息 -->
			<view v-if="showDebugInfo" class="debug-info">
				<text class="debug-title">调试信息</text>
				<text>API地址: {{ apiBaseUrl }}</text>
				<text>API状态: {{ apiStatus }}</text>
				<button class="debug-btn" @tap="testConnection">测试连接</button>
			</view>
		</view>
		
		<!-- 注册弹窗 -->
		<uni-popup ref="registerPopup" type="center">
			<view class="popup-content">
				<view class="popup-title">注册新账号</view>
				
				<!-- 注册错误信息显示 -->
				<view v-if="registerErrorMsg" class="error-message">
					<text>{{ registerErrorMsg }}</text>
				</view>
				
				<view class="form-item">
					<input v-model="registerForm.username" placeholder="请输入用户名" />
				</view>
				<view class="form-item">
					<input v-model="registerForm.password" type="password" placeholder="请输入密码" />
				</view>
				<view class="form-item">
					<input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" />
				</view>
				<view class="form-actions">
					<button @tap="cancelRegister" :disabled="isRegistering">取消</button>
					<button @tap="register" :disabled="isRegistering" type="primary">
						{{ isRegistering ? '注册中...' : '注册' }}
					</button>
				</view>
			</view>
		</uni-popup>
		
		<!-- 开发环境调试按钮 -->
		<view class="debug-toggle" @tap="toggleDebug">
			<text>{{ showDebugInfo ? '隐藏调试' : '显示调试' }}</text>
		</view>
	</view>
</template>

<script>
	import api from '../../utils/api.js';
	import config from '../../utils/config.js';
	import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
	
	export default {
		components: {
			uniPopup
		},
		data() {
			return {
				username: '',
				password: '',
				errorMsg: '',  // 添加错误消息字段
				registerErrorMsg: '',  // 添加注册错误消息字段
				isLoading: false,  // 登录加载状态
				isRegistering: false, // 注册加载状态
				showDebugInfo: false, // 是否显示调试信息
				apiBaseUrl: config.apiBaseUrl, // API基址
				apiStatus: '未测试',  // API连接状态
				registerForm: {
					username: '',
					password: '',
					confirmPassword: ''
				}
			}
		},
		onLoad() {
			// 清除可能存在的旧token
			uni.removeStorageSync('token');
			uni.removeStorageSync('userId');
			uni.removeStorageSync('username');
			console.log('登录页面加载，已清除旧token');
			
			// 在开发环境中预填充测试账号
			// #ifdef DEBUG
			this.username = 'admin';
			this.password = '123456';
			// #endif
		},
		methods: {
			toggleDebug() {
				this.showDebugInfo = !this.showDebugInfo;
			},
			
			// 测试API连接
			testConnection() {
				this.apiStatus = '测试中...';
				
				// 尝试访问API根路径
				uni.request({
					url: this.apiBaseUrl,
					method: 'GET',
					success: (res) => {
						console.log('API测试结果:', res);
						this.apiStatus = `可连接 (${res.statusCode})`;
					},
					fail: (err) => {
						console.error('API连接失败:', err);
						this.apiStatus = `连接失败: ${err.errMsg}`;
					}
				});
			},
			
			login() {
				this.errorMsg = '';  // 清除之前的错误信息
				
				if (!this.username || !this.password) {
					this.errorMsg = '请输入用户名和密码';
					uni.showToast({
						title: this.errorMsg,
						icon: 'none'
					});
					return;
				}
				
				console.log('尝试登录...');
				this.isLoading = true;  // 设置加载状态
				
				api.login(this.username, this.password)
					.then(response => {
						this.isLoading = false;  // 清除加载状态
						console.log('登录响应:', response);
						
						if (response.code === 200) {
							// 存储登录信息
							uni.setStorageSync('token', response.data.token);
							uni.setStorageSync('userId', response.data.userId);
							uni.setStorageSync('username', response.data.username);
							
							console.log('登录成功，已保存token');
							
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							});
							
							// 跳转到首页
							uni.reLaunch({
								url: '/pages/index/index'
							});
						} else if (response.code === 403) {
							// 特别处理CORS错误
							this.errorMsg = '服务器拒绝访问，可能是跨域问题，请联系管理员';
							console.error('CORS错误:', this.errorMsg);
						} else {
							this.errorMsg = response.message || '登录失败，用户名或密码错误';
							console.error('登录失败:', this.errorMsg);
							uni.showToast({
								title: this.errorMsg,
								icon: 'none'
							});
						}
					})
					.catch(error => {
						this.isLoading = false;  // 清除加载状态
						this.errorMsg = '网络请求失败，请检查网络连接或服务器状态';
						console.error('登录请求异常:', error);
						uni.showToast({
							title: this.errorMsg,
							icon: 'none'
						});
					});
			},
			showRegister() {
				// 清空注册表单
				this.registerForm = {
					username: '',
					password: '',
					confirmPassword: ''
				};
				this.registerErrorMsg = '';  // 清除之前的错误信息
				
				// 打开注册弹窗
				this.$refs.registerPopup.open();
			},
			cancelRegister() {
				this.$refs.registerPopup.close();
			},
			register() {
				this.registerErrorMsg = '';  // 清除之前的错误信息
				
				if (!this.registerForm.username || !this.registerForm.password) {
					this.registerErrorMsg = '请输入用户名和密码';
					uni.showToast({
						title: this.registerErrorMsg,
						icon: 'none'
					});
					return;
				}
				
				if (this.registerForm.password !== this.registerForm.confirmPassword) {
					this.registerErrorMsg = '两次密码输入不一致';
					uni.showToast({
						title: this.registerErrorMsg,
						icon: 'none'
					});
					return;
				}
				
				console.log('尝试注册...');
				this.isRegistering = true;  // 设置注册中状态
				
				api.register(this.registerForm.username, this.registerForm.password)
					.then(response => {
						this.isRegistering = false;  // 清除注册中状态
						console.log('注册响应:', response);
						
						if (response.code === 200) {
							uni.showToast({
								title: '注册成功',
								icon: 'success'
							});
							
							// 关闭弹窗
							this.$refs.registerPopup.close();
							
							// 填充登录表单
							this.username = this.registerForm.username;
							this.password = this.registerForm.password;
						} else if (response.code === 403) {
							// 特别处理CORS错误
							this.registerErrorMsg = '服务器拒绝访问，可能是跨域问题，请联系管理员';
							console.error('CORS错误:', this.registerErrorMsg);
						} else {
							this.registerErrorMsg = response.message || '注册失败，用户名可能已存在';
							console.error('注册失败:', this.registerErrorMsg);
							uni.showToast({
								title: this.registerErrorMsg,
								icon: 'none'
							});
						}
					})
					.catch(error => {
						this.isRegistering = false;  // 清除注册中状态
						this.registerErrorMsg = '网络请求失败，请检查网络连接或服务器状态';
						console.error('注册请求异常:', error);
						uni.showToast({
							title: this.registerErrorMsg,
							icon: 'none'
						});
					});
			}
		}
	}
</script>

<style>
	.login-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		padding: 50rpx;
		background-color: #f8f9fa;
	}
	
	.login-header {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 80rpx;
		margin-top: 100rpx;
	}
	
	.logo {
		width: 150rpx;
		height: 150rpx;
		margin-bottom: 30rpx;
	}
	
	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
	}
	
	.login-form {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.label {
		display: block;
		margin-bottom: 10rpx;
		color: #666;
		font-size: 28rpx;
	}
	
	.form-item input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.form-actions {
		display: flex;
		flex-direction: column;
		margin-top: 50rpx;
	}
	
	.login-btn {
		height: 90rpx;
		line-height: 90rpx;
		background-color: #007AFF;
		color: #fff;
		font-size: 32rpx;
		border-radius: 45rpx;
	}
	
	.register-btn {
		margin-top: 30rpx;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #fff;
		color: #007AFF;
		font-size: 32rpx;
		border: 1rpx solid #007AFF;
		border-radius: 45rpx;
	}
	
	.popup-content {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 40rpx;
		width: 600rpx;
	}
	
	.popup-title {
		text-align: center;
		font-size: 36rpx;
		margin-bottom: 40rpx;
		font-weight: bold;
	}
	
	/* 错误信息样式 */
	.error-message {
		background-color: #fef0f0;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		text-align: center;
	}
	
	.error-message text {
		color: #f56c6c;
		font-size: 26rpx;
	}
	
	/* 调试信息样式 */
	.debug-info {
		margin-top: 40rpx;
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 8rpx;
		border: 1rpx dashed #ddd;
	}
	
	.debug-info text {
		display: block;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 10rpx;
	}
	
	.debug-title {
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
	}
	
	.debug-btn {
		margin-top: 20rpx;
		font-size: 24rpx;
		padding: 10rpx;
		background-color: #f1f1f1;
	}
	
	.debug-toggle {
		position: absolute;
		bottom: 30rpx;
		right: 30rpx;
		background-color: rgba(0, 0, 0, 0.1);
		padding: 10rpx 20rpx;
		border-radius: 30rpx;
	}
	
	.debug-toggle text {
		font-size: 24rpx;
		color: #666;
	}
</style> 